<template>
  <div>
    <div class="flex items-center gap-2 mb-3">
      <select v-model="asset" class="border rounded p-2">
        <option v-for="a in assets" :key="a" :value="a">{{a}}</option>
      </select>
      <div class="flex gap-2 text-sm">
        <label class="flex items-center gap-1"><input type="checkbox" v-model="showMA5"/> MA5</label>
        <label class="flex items-center gap-1"><input type="checkbox" v-model="showMA10"/> MA10</label>
      </div>
    </div>
    <v-chart ref="chartRef" :option="option" autoresize style="height:420px; width:100%" />
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { CandlestickChart, LineChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, DataZoomComponent, LegendComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import { getKlineData, calcMA } from '../api/mockData.js'
import { useResize } from '../composables/useResize'

const chartRef = ref(null)
useResize(() => chartRef.value?.resize())

use([CanvasRenderer, CandlestickChart, LineChart, GridComponent, TooltipComponent, DataZoomComponent, LegendComponent])

const assets = ['BTC','ETH']
const asset = ref('BTC')
const raw = ref([])
const showMA5 = ref(true)
const showMA10 = ref(true)

watch(asset, ()=> { raw.value = getKlineData(asset.value, '1M') }, { immediate: true })

const option = computed(()=> ({
  tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
  legend: { data: ['Kline', 'MA5', 'MA10'] },
  xAxis: { type: 'category', data: raw.value.map(i=>i[0]), scale: true },
  yAxis: { scale: true, splitArea: { show: true } },
  grid: [{ left: '6%', right: '4%', top: 20, height: '65%' }],
  dataZoom: [{ type: 'inside', start: 50, end: 100 }, { start: 50, end: 100 }],
  series: [
    { name: 'Kline', type: 'candlestick', data: raw.value.map(i=>i.slice(1,5)) },
    showMA5.value ? { name: 'MA5', type: 'line', data: calcMA(raw.value,5), smooth: true, lineStyle: { width:1 } } : null,
    showMA10.value ? { name: 'MA10', type: 'line', data: calcMA(raw.value,10), smooth: true, lineStyle: { width:1 } } : null
  ].filter(Boolean)
}))
</script>
